<template>
  <!-- 页面顶部添加搜索框 -->
  <div class="relative">
    <input 
        type="text" 
        v-model="searchKey" 
        placeholder="搜索订单ID" 
    >
  </div>
  
  <div>
    <h1>订单列表</h1>
    <el-button  type="primary" @click="goback"  class="top-right-button">返回</el-button>
    <table>
      <thead>
        <tr>
          <th>订单ID</th>
          <th>订单状态</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="order in orders" :key="order.id">
          <td>{{ order.id }}</td>
          <td>{{ getOrderStatusText(order.status) }}</td>
          <td>{{ formatDateTime(order.createTime) }}</td>
          <td>
            <!-- 待支付状态操作 -->
            <button v-if="order.status === OrderStatus.WAITING_PAYMENT" @click="fakePay(order.id)">支付订单</button>
            <button v-if="order.status === OrderStatus.WAITING_PAYMENT" @click="cancelOrder(order.id)">取消订单</button>
            
            <!-- 已支付状态操作 -->
            <button v-if="order.status === OrderStatus.PAID" @click="applyRefund(order.id)">申请退款</button>
            <button v-if="order.status === OrderStatus.PAID" @click="markShipped(order.id)">标记发货</button>
            
            <!-- 申请退款状态操作 -->
            <button v-if="order.status === OrderStatus.REFUND_APPLIED" @click="cancelRefund(order.id)">取消退款申请</button>
            
            <!-- 已发货状态操作 -->
            <button v-if="order.status === OrderStatus.SHIPPED" @click="confirmReceive(order.id)">确认收货</button>
            
            <!-- 操作列新增删除按钮 -->
            <button v-if="order.status === OrderStatus.COMPLETED || order.status === OrderStatus.CANCELLED" @click="deleteOrder(order.id)" >删除订单</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import router from '@/router';
import { store } from '@/common/store';

// 定义订单状态
const OrderStatus = {
  WAITING_PAYMENT: 1,
  PAID: 2,
  SHIPPED: 3,
  COMPLETED: 4,
  CANCELLED: 5,
  REFUND_APPLIED: 6
};

//orders装订单，searchKey装订单号
const orders = ref<any[]>([]);
const searchKey = ref<string>('');

// 获取订单列表
function getOrders() {
    //有搜索词查搜索，没搜索词查全部
const url = searchKey.value ? '/orderapi/orders/search' : '/orderapi/orders' +'/'+store.userinfo.id;
    //向后端要数据
    axios.get(url, { 
        params: { search: searchKey.value } 
    })
    .then(res => {
        if (res.data.code === 200) {
            orders.value = res.data.data;
        } else {
            ElMessage.error(res.data.message);
        }
    })
}

// 实时搜索
watch(searchKey, () => {
  getOrders();
});

// 假支付
function fakePay(orderId:number) {
    axios.post(`/orderapi/orders/${orderId}/fakePay`)
    .then(res => {
        if (res.data.code === 200) {
            ElMessage.success('支付成功');
            return getOrders();
        } else {
            ElMessage.error(res.data.message);
            throw new Error(res.data.message);
        }
    })
}

// 取消订单
function cancelOrder(orderId:number) {
    axios.post(`/orderapi/orders/${orderId}/cancel`)
    .then(res => {
        if (res.data.code === 200) {
            ElMessage.success('订单取消成功');
            return getOrders();
        } else {
            ElMessage.error(res.data.message);
            throw new Error(res.data.message);
        }
    })
}

// 申请退款
function applyRefund(orderId:number) {
    axios.post(`/orderapi/orders/${orderId}/applyRefund`)
    .then(res => {
        if (res.data.code === 200) {
            ElMessage.success('退款申请成功');
            return getOrders();
        } else {
            ElMessage.error(res.data.message);
            throw new Error(res.data.message);
        }
    })
}

// 取消退款申请
function cancelRefund(orderId:number) {
    axios.post(`/orderapi/orders/${orderId}/cancelRefund`)
    .then(res => {
        if (res.data.code === 200) {
            ElMessage.success('取消退款申请成功');
            return getOrders();
        } else {
            ElMessage.error(res.data.message);
            throw new Error(res.data.message);
        }
    })
}

// 确认收货
function confirmReceive(orderId:number) {
    axios.post(`/orderapi/orders/${orderId}/confirmReceive`)
    .then(res => {
        if (res.data.code === 200) {
            ElMessage.success('确认收货成功');
            return getOrders();
        } else {
            ElMessage.error(res.data.message);
            throw new Error(res.data.message);
        }
    })
}

// 标记发货
function markShipped(orderId:number) {
    axios.post(`/orderapi/orders/${orderId}/markShipped`)
    .then(res => {
        if (res.data.code === 200) {
            ElMessage.success('标记发货成功');
            return getOrders();
        } else {
            ElMessage.error(res.data.message);
            throw new Error(res.data.message);
        }
    })
}

// 删除订单
function deleteOrder(orderId:number) {
    if (!confirm('确定要删除该订单吗？此操作不可恢复！')) return;
    
    axios.delete(`/orderapi/orders/${orderId}`)
    .then(res => {
        if (res.data.code === 200) {
            ElMessage.success('订单删除成功');
            return getOrders();
        } else {
            ElMessage.error(res.data.message);
            throw new Error(res.data.message);
        }
    })
}

// 订单状态转为文本
function getOrderStatusText(status: number): string {
  switch (status) {
    case OrderStatus.WAITING_PAYMENT: return "待支付";
    case OrderStatus.PAID: return "已支付";
    case OrderStatus.SHIPPED: return "已发货";
    case OrderStatus.COMPLETED: return "已完成";
    case OrderStatus.CANCELLED: return "已取消";
    case OrderStatus.REFUND_APPLIED: return "申请退款";
    default: return "未知状态";
  }
}



// 格式化时间
function formatDateTime(dateTime: string | null): string {
  if (!dateTime) return "-";
  return new Date(dateTime).toLocaleString();
}
function goback(){
  router.back();
}
//获取数据
getOrders();

</script>
<style scoped>
/* 搜索框样式 */
input[type="text"] {
    width: 100%;
    padding: 10px;
    font-size: 16px;
    border-radius: 5px;
    border: 1px solid #ccc;
    box-sizing: border-box;
    transition: all 0.3s ease;
}

input[type="text"]:focus {
    border-color: #409EFF;
    box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}

input[type="text"]::placeholder {
    color: #aaa;
}

input[type="text"]:focus::placeholder {
    color: #409EFF;
}

/* 标题样式 */
h1 {
    font-size: 24px;
    color: #333;
    margin-bottom: 20px;
}

/* 表格样式 */
table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
}

table th, table td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #ddd;
}

table th {
    background-color: #f4f4f4;
    font-weight: bold;
}

table tr:hover {
    background-color: #f9f9f9;
}

table td {
    font-size: 14px;
    color: #333;
}

/* 按钮样式 */
button {
    padding: 8px 16px;
    font-size: 14px;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-right: 10px;
    margin-top: 5px;
}

/* 操作按钮颜色 */
button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
}

/* 不同状态按钮颜色 */
button:nth-of-type(1) {
    background-color: #409EFF; /* 支付订单 */
    color: white;
}

button:nth-of-type(2) {
    background-color: #f56c6c; /* 取消订单 */
    color: white;
}

button:nth-of-type(3) {
    background-color: #e6a23c; /* 申请退款 */
    color: white;
}

button:nth-of-type(4) {
    background-color: #67c23a; /* 标记发货 */
    color: white;
}

button:nth-of-type(5) {
    background-color: #909399; /* 删除订单 */
    color: white;
}

/* 按钮悬停效果 */
button:hover {
    opacity: 0.8;
}

/* 响应式设计 */
@media (max-width: 768px) {
    input[type="text"] {
        width: 100%;
    }

    table th, table td {
        font-size: 12px;
        padding: 8px;
    }

    h1 {
        font-size: 20px;
    }

    button {
        padding: 6px 12px;
        font-size: 12px;
    }
}
.top-right-button {
  position: absolute;
  top: 10px; /* 距离顶部10像素 */
  right: 10px; /* 距离右侧10像素 */
  z-index: 100; /* 确保按钮在其他元素上方 */
}


</style>